package top.btcmarket.gateway.config;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

/**
 * 如果网关后面的微服务挂了，zuul允许定义一个fallback类，用于熔断处理，参考下面的代码：
 * @ClassName:  ServiceConsumerFallbackProvider   
 * @Description:TODO(这里用一句话描述这个类的作用)   
 * @author: pengwei
 * @date:   2017年11月14日 下午4:42:45   
 * 
 *  getRoute 表示 serverId 配置文件里面的
 */
@Component
public class ServiceConsumerFallbackProvider implements ZuulFallbackProvider {
 
    @Override
    public String getRoute() {
        return "btcmarket-security";
    }
 
    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }
 
            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
 
            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }
 
            @Override
            public void close() {
 
            }
 
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("btcmarket-security 不可用，熔断保护".getBytes());
            }
 
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                MediaType mt = new MediaType("application", "txt", Charset.forName("UTF-8"));
                // MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));  getBody 的内容不是 json的，postman 返回的会显示不正常
                headers.setContentType(mt);
                return headers;
            }
        };
    }
}
